<template>
    <div :class="['bookmarker', 'h-screen', 'flex', 'flex-col', 'bg-[#333]', { 'fullscreen': isFullScreen }]"
        v-loading="loading">
        <div class="flex flex-row items-center  h-11 bg-[#666] text-white">
            <div class="px-2 bookname">《{{ bookName }}》</div>
            <div class="flex flex-row flex-1"></div>
            <div class="flex pr-5">
                <el-button size="small" text bg @click="toggleFullscreen">{{ isFullScreen ? '退出全屏' : '全屏编辑' }}</el-button>
            </div>
        </div>
        <div class="flex flex-row flex-1 wrapper" ref="wrapper" style="height:calc(100vh - 48px)">
            <div class="pr-1 sidebar" :style="{ width: splitterLeft }">
                <LeftSideBarVue></LeftSideBarVue>
            </div>
            <div class="splitter" ref="splitter" @mousedown.prevent="startDrag" @touchstart.prevent="startDrag"
                :style="{ left: splitterLeft }">
            </div>
            <div class="flex flex-row flex-1 w-full h-full ml-1 marker">
                <BookMarkerVue v-if="!loading"></BookMarkerVue>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import BookMarkerVue from './components/BookMarker.vue'
import LeftSideBarVue from './components/LeftSideBar.vue'
import { useRouter } from "vue-router";
import { useBookEditorStore, type BookMenu, type Book } from "@/stores/modules/wisdbookMarker";
import { storeToRefs } from "pinia";
import { loadPagesByBookId } from "@/api/wisdbook/marker";
import { loadMenu } from "@/api/wisdbook/menu";


const router = useRouter();
const editorStore = useBookEditorStore();
const bookId: any = ref("2");
const { bookName, bookmenu } = storeToRefs(useBookEditorStore());
const loading = ref(true);
const isFullScreen = ref(false);

//获取URl参数
bookId.value = router.currentRoute.value.query.bookId;

//加载整本书的所有页面
loadPagesByBookId({ bookId: bookId.value }).then((data: any) => {
   
    let bookData = data as Book
    console.log("书籍数据:", bookData);
    // 初始化一些默认参数
    bookData.pages.forEach((element: any) => {
        element.edit = false;
    })
    editorStore.setBook(bookData);
    loading.value = false;

    loadMenu({ bookId: bookId.value }).then((data: any) => {
        console.log("菜单:", data);
        let menus = data as BookMenu[]
        setMenuDefaultData(menus)
        bookmenu.value = [{
            id: 0,
            pid: 0,
            text: bookName.value,
            bookId: bookId.value,
            pageIds: '',
            canDel: false,
            canEdit: false,
            canDrag: false,
            sort: 1,
            children: data
        }]
    });
});


// 初始化目录的默认参数值
const setMenuDefaultData = (menus: BookMenu[]) => {
    menus.forEach((element: any) => {
        element.canDel = true;
        element.canDrag = true;
        element.canEdit = true;
        setMenuDefaultData(element.children)
    })
    menus
}

const toggleFullscreen = () => {
    if (isFullScreen.value) {
        isFullScreen.value = false;
    } else {
        isFullScreen.value = true;
    }
}



// 分栏拖动相关配置
const isDragging = ref(false)
const startX = ref(0)
const splitterLeftMax = 0.4;  //分隔栏最大位置
const splitterLeftMin = 0.15; //分隔栏最小位置
const splitterLeft = ref(splitterLeftMin * 100 + '%') // 分隔栏默认位置
const wrapper = ref<HTMLElement | null>(null);
let containerWidth = computed(() => wrapper.value ? wrapper.value.clientWidth || wrapper.value.offsetWidth : 0).value;
const getClientX = (ev: MouseEvent | TouchEvent) => {
    if (ev.type.startsWith('touch')) {
        return (ev as TouchEvent).touches[0].clientX
    } else {
        return (ev as MouseEvent).clientX
    }
}

const startDrag = (ev: MouseEvent | TouchEvent) => {
    isDragging.value = true
    startX.value = getClientX(ev)
    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('touchmove', handleDrag)
    document.addEventListener('mouseup', stopDrag)
    document.addEventListener('touchend', stopDrag)
}

const handleDrag = (ev: MouseEvent | TouchEvent) => {
    if (isDragging.value) {
        const x = getClientX(ev)
        const deltaX = x - startX.value
        const currentLeft = parseFloat(splitterLeft.value)
        const newLeft = currentLeft + deltaX / containerWidth * 100
        const clampedLeft = Math.max(splitterLeftMin * 100, Math.min(splitterLeftMax * 100, newLeft))
        // console.log("拖动：startX:",startX.value," deltaX:",deltaX," currentLeft:", currentLeft, " newLeft:", newLeft, " clampedLeft:", clampedLeft, " containerWidth:", containerWidth);
        splitterLeft.value = `${clampedLeft}%`
        startX.value = x
    }
}

const stopDrag = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', handleDrag)
    document.removeEventListener('touchmove', handleDrag)
    document.removeEventListener('mouseup', stopDrag)
    document.removeEventListener('touchend', stopDrag)
}

onMounted(() => {
    containerWidth = (wrapper.value ? wrapper.value.clientWidth || wrapper.value.offsetWidth : 0)
    document.addEventListener('mouseup', stopDrag)
    document.addEventListener('touchend', stopDrag)
})

onUnmounted(() => {
    document.removeEventListener('mouseup', stopDrag)
    document.removeEventListener('touchend', stopDrag)
})
// end拖动操作

</script>
<style lang="scss" scoped>
.wrapper {
    position: relative;
    height: 100%;
}

.splitter {
    position: absolute;
    top: 0;
    bottom: 0;
    width: 4px;
    cursor: col-resize;
    background-color: #000;
    z-index: 2000;
}

.fullscreen {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 100vw;
    z-index: 1000;
}
</style>
